<template>
  <div>
    <a-table :columns="columns" :data-source="value" bordered>
      <template #bodyCell="{ column, index }">
        <template v-if="column.dataIndex === 'oper'">
          <a class="text-red-400" @click="delByIndex(index)">删除</a>
        </template>
      </template>
      <template #title>
        <a-button type="primary" @click="open">新增设备</a-button>
      </template>
    </a-table>
    <a-modal v-model:visible="deviceSelectVisible" :width="900" title="选择设备" @ok="ok">
      <device-select ref="deviceListIns" v-model:value="selectDeviceIds" />
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { message } from "ant-design-vue";
import { ref } from "vue";
import type { DeviceItem, TollBoothDeviceItem } from "/@/api/main/civilizedService/models";
import { SelectExpose } from "/@/types/components";
import { cloneDeep } from "lodash-es";

const props = defineProps<{
  value: TollBoothDeviceItem[];
}>();

const emits = defineEmits(["change"]);

const columns = ref([
  {
    title: "设备ID",
    dataIndex: "deviceId",
  },
  {
    title: "设备名称",
    dataIndex: "deviceName",
  },
  {
    title: "操作",
    dataIndex: "oper",
  },
]);
function delByIndex(index: number) {
  const copyValue = cloneDeep(props.value);
  copyValue.splice(index, 1);
  emits("change", copyValue);
}

const deviceSelectVisible = ref(false);
const selectDeviceIds = ref<number[]>([]);
const deviceListIns = ref<SelectExpose<DeviceItem>>();
function open() {
  const ids = props.value.map((el) => el.deviceId);
  selectDeviceIds.value = ids;
  if (deviceListIns.value) {
    const items: DeviceItem[] = props.value.map((el) => ({
      id: el.deviceId,
      videoCameraName: el.deviceName,
    }));
    deviceListIns.value.setSelectedItems(items);
  }
  deviceSelectVisible.value = true;
}
function ok() {
  if (selectDeviceIds.value.length === 0) {
    return message.info("请至少选择一个设备");
  }
  if (deviceListIns.value) {
    const items = deviceListIns.value.getSelecedItems();
    const tollBoothDeviceItems: TollBoothDeviceItem[] = items.map((el) => ({
      deviceId: el.id as number,
      deviceName: el.videoCameraName as string,
    }));
    emits("change", tollBoothDeviceItems);
  }
  deviceSelectVisible.value = false;
}
</script>
